import datetime

from app.db.redis import r
from app.core.BaseResponse import UnicornException
from app.core.random_str import getRandomNum


def get_current_date():
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                          microseconds=now.microsecond)
    last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
    current_time = last_today - now
    m = current_time.seconds
    return m


async def captcha_service(mobile, types):
    """
    发送验证码服务
    :param mobile:
    :param types: 1 为app  2 为pc
    :return:
    """
    r.incr(f"{mobile}:code:totals")
    r.expire(f"{mobile}:code:totals", get_current_date())
    count = r.get(f"{mobile}:code:totals").decode()
    code = getRandomNum(4)
    if int(count) >= 8:
        raise UnicornException(-1, errmsg="今日发送验证码次数已用完~")
    if int(types) == 1:
        r.set(f"{mobile}:app:captcha", code, 300)
        # 调用短信发送服务
        redis_user = r.get(f"{mobile}:app:captcha")
        if not redis_user:
            raise UnicornException(-1, errmsg="发送失败")
        return redis_user
    else:
        r.set(f"{mobile}:pc:captcha", code, 300)
        # 调用短信发送服务
        redis_user = r.get(f"{mobile}:pc:captcha")
        if not redis_user:
            raise UnicornException(-1, errmsg="发送失败")
        return redis_user


